/*
 * @Author: Clark
 * @Email: haixuanwoTxh@gmail.com
 * @Date: 2021-11-27 11:34:52
 * @LastEditors: Clark
 * @LastEditTime: 2021-12-11 20:23:49
 * @Description: 客户管理器
 */

#ifndef CLIENT_MANAGER_H
#define CLIENT_MANAGER_H

#include <string>
#include <map>
#include "user.h"

class ClientManager
{
public:
    ClientManager()
    {
        userMap = new std::map<u_int32_t, User>;
        userMap->clear();
    }

    bool add_user(User &user)
    {
        userMap->insert(std::make_pair(user.ID, user));
        return true;
    }

    bool delete_user(int userID)
    {
        userMap->erase(userID);
        return true;
    }

    bool set_status(u_int32_t userID, LoginStatus loginStatus)
    {
        auto user = userMap->find(userID);
        user->second.loginStatus = loginStatus;
        return true;
    }

    bool get_status(u_int32_t userID, LoginStatus &loginStatus)
    {
        auto user = userMap->find(userID);
        loginStatus = user->second.loginStatus;
        return true;
    }

    bool find_user_by_account(std::string &account, User &user)
    {
        for (auto _map : *userMap)
        {
            if (0 == account.compare(_map.second.account))
            {
                user = _map.second;
                return true;
            }
        }

        return false;
    }

    User find_userID(u_int32_t &userID)
    {
        auto user = userMap->find(userID);
        return user->second;
    }

    u_int32_t get_new_user_ID()
    {
        u_int32_t userID = 0;

        // 获取最大的userID，最后+1
        for(auto _map : *userMap)
        {
            if (_map.first > userID)
                userID = _map.first;
        }

        // 用户数达到最大值，出bug
        userID++;
        return userID;
    }

    ~ClientManager()
    {
        delete userMap;
    }
private:
    std::map<u_int32_t, User> *userMap;  // <userID, User>
};

#endif
